#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "options.h"

struct capture_options options = {
    .ifname = NULL, 
    .verbose = 1,
    .is_file = 0,
    .engine = CAPTURE_ENGINE_PCAP,
};

void options_version(void)
{
    printf("%s version %s\n", PACKAGE_NAME, PACKAGE_VERSION);
    fflush(stdout);
}

void options_help(void)
{
    options_version();
    printf("Usage: %s [OPTION] ...\n", PACKAGE_NAME);
    printf("Capture packet and analysis\n");
    printf("    -e, --engine=[ENGINE]     capture engine: recv, mmap, pcap, dpdk\n");
    printf("    -f, --file=[FILE]         capture from pcap file path\n");
    printf("    -i, --ifname=[IFNAME]     capture from interface name\n");
    printf("    -v, --verbose=[VERBOSE]   verbose output\n");
    printf("    -q, --quiet               quiet output\n");
    printf("    -V, --version             print version\n");
    printf("    -h, --help                print this help\n");
    fflush(stdout);
}

int options_parse(int argc, char *argv[])
{
    int opt;
    const char *short_options = "e:f:hi:qv:V";
    const struct option long_options[] = {
        { "help",    no_argument, NULL, 'h' },
        { "version", no_argument, NULL, 'V' },
        { "quiet",   no_argument, NULL, 'q' },
        { "ifname",  required_argument, NULL, 'i' },
        { "file",    required_argument, NULL, 'f' },
        { "engine",  required_argument, NULL, 'e' },
        { "verbose", optional_argument, NULL, 'v' },
        {NULL, 0, NULL, 0} ,
    };
    opterr = 0;
    while((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)
    {
        switch(opt) {
        case 'e':
            if (strcmp(optarg, "dpdk") == 0) {
                options.engine = CAPTURE_ENGINE_DPDK;
            } else if (strcmp(optarg, "pcap") == 0) {
                options.engine = CAPTURE_ENGINE_PCAP;
            } else if (strcmp(optarg, "mmap") == 0) {
                options.engine = CAPTURE_ENGINE_MMAP;
            } else if (strcmp(optarg, "recv") == 0) {
                options.engine = CAPTURE_ENGINE_RECV;
            } else {
                options.engine = CAPTURE_ENGINE_UNKNOWN;
            }
            break;
        case 'f':
            options.is_file = 1;
        case 'i':
            options.ifname = optarg;
            break;
        case 'v':
            options.verbose = strlen(optarg);
            break;
        case 'q':
            options.verbose = 0;
            break;
        case 'h':
            options_help();
            exit(0);
        case 'V':
            options_version();
            exit(0);
        case '?':
            printf("Unknown option -%c\n\n", optopt);
            options_help();
            exit(0);
        default:
            printf("What happened?\n\n");
            options_help();
            exit(0);
        }
    }
    printf("optind=%d,argc=%d\n", optind, argc);
    return 0;
}
